package com.gs.practice.thread.javathreads.ch02.ex7;

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;

import com.gs.practice.thread.javathreads.ch02.CharacterDisplayCanvas;
import com.gs.practice.thread.javathreads.ch02.CharacterEvent;
import com.gs.practice.thread.javathreads.ch02.CharacterListener;
import com.gs.practice.thread.javathreads.ch02.CharacterSource;

public class AnimatedCharacterDisplayCanvas extends CharacterDisplayCanvas
	implements CharacterListener, Runnable{

	/**
	 * 
	 */
	private static final long serialVersionUID = 16654684654L;
	private volatile boolean done = false;
	private int curX = 0;
	
	public AnimatedCharacterDisplayCanvas() {
		
	}
	
	public AnimatedCharacterDisplayCanvas(CharacterSource source){
		super(source);
	}
	
	public void setDone(boolean done) {
		this.done = done;
	}

	@Override
	public void run() {
		while(!done){
			repaint();
			try {
				Thread.sleep(100);
			} catch (InterruptedException e) {
				return;
			}
		}
	}

	@Override
	public synchronized void newCharacter(CharacterEvent event) {
		curX = 0;
		tmpChar[0] = (char) event.getCharacter();
		repaint();
	}

	@Override
	public synchronized void paintComponent(Graphics graphics) {
		Graphics2D g = (Graphics2D) graphics;
        if(null != g){
        	RenderingHints hints = new RenderingHints(
    				RenderingHints.KEY_ANTIALIASING,
    				RenderingHints.VALUE_ANTIALIAS_ON);
    		hints.add(new RenderingHints(RenderingHints.KEY_RENDERING,
    				RenderingHints.VALUE_RENDER_QUALITY));

    		Graphics2D g2d = (Graphics2D) g;
    		g2d.setRenderingHints(hints);
        }
		g.setColor(Color.BLACK);
		Dimension dimension = getSize();
		g.clearRect(0, 0, dimension.width, dimension.height);
		if(tmpChar[0] == 0)
			return;
		int charWidth = fontMetrics.charWidth((int) tmpChar[0]);
		g.drawChars(tmpChar, 0, 1, Math.max(100, curX+=3), fontHeight);
	}

	
}
